/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc.server.impl;

import cn.yzc.mapper.GoodsMapper;
import cn.yzc.mapper.OrderdetailsMapper;
import cn.yzc.mapper.OrdersMapper;
import cn.yzc.pojo.Goods;
import cn.yzc.pojo.Orderdetails;
import cn.yzc.pojo.Orders;
import cn.yzc.server.OrdersServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: redis - OrdersServerImpl</p>
 * <p>Powered by yzc On 2023-12-14 09:22:53</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@Service
public class OrdersServerImpl implements OrdersServer {

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    OrderdetailsMapper orderdetailsMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Transactional
    @Override
    public int save(Orders orders) {
        String serial = String.valueOf(System.currentTimeMillis());
        int rs =0;
        orders.setOid(serial);
        List<Orderdetails> orderdetailsList = orders.getOrderdetailsList();
        orderdetailsList.forEach(orderdetails -> {
            orderdetails.setOid(serial);
             int num =  goodsMapper.queryNum(orderdetails.getGoodid());
             int number = orderdetails.getNumber();
             int newNum = num - number;
            goodsMapper.update(orderdetails.getGoodid(),newNum);
        });
        String key = "order:"+serial;
        if (!redisTemplate.hasKey(key)){
            redisTemplate.opsForValue().set(key,orders,1,TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(serial,orders);
            rs = 1;
        }else {
            rs =0;
        }
        return rs;
    }

    @Override
    public int pay(String oid) {
        String orderNo = "order:"+oid;
        int rs = 0;
        if (redisTemplate.hasKey(orderNo) && redisTemplate.hasKey(oid)){
          Orders orders = (Orders) redisTemplate.opsForValue().get(oid);
         rs =  ordersMapper.save(orders);
         rs = orderdetailsMapper.save(orders.getOrderdetailsList());
         redisTemplate.delete(orderNo);
         redisTemplate.delete(oid);
        }
        return rs;
    }

    @Override
    public Orders queryOid(String oid) {
        Orders orders = (Orders) redisTemplate.opsForValue().get(oid);
        if (orders == null) {
            orders = ordersMapper.queryOid(oid);
            redisTemplate.opsForValue().set(oid,orders,3,TimeUnit.MINUTES);
        }
        return orders;
    }
}

